package org.myself.meeting.interceptor;

import org.myself.meeting.model.Employee;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//拦截器
public class PremissInterceptor implements HandlerInterceptor {
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURL = request.getRequestURI();
        if("/".equals(requestURL) ||"/register".equals(requestURL) ||"/dologin".equals(requestURL) || "/doreg".equals(requestURL)){
            return true;
        }
        if("/webSocketServer".equals(requestURL) ||"/sockjs/webSocketServer".equals(requestURL) ){
            return true;
        }
        if("/websocket".equals(requestURL)){
            return true;
        }

        HttpSession session= request.getSession(true);
        Employee currentuser = (Employee) session.getAttribute("currentuser");
        if (antPathMatcher.match("/managerboss/**",requestURL)){
            //判断权限  登陆不需要
            if ("/managerboss/login".equals(requestURL) || "/managerboss/dologin".equals(requestURL)){
                return true;
            }else{
                if (currentuser != null){
                    return true;
                }
            }
            response.sendRedirect("/managerboss/login");
            return false;
        }
        if (antPathMatcher.match("/admin/**",requestURL)){
            if(currentuser!= null ){
                if (currentuser.getRole() == 2){
                    return true;
                }
                response.getWriter().write("403 error");
                return false;
            }
        }else{
            if (currentuser != null){
                return true;
            }
        }

//        if(session.getAttribute("IP")==request.getRemoteAddr()){
//            return true;
//        }

        response.sendRedirect("/");
        return false;
    }
}
